define(function () {

  /**
   * 通过起止时间计算时间段格子的位置
   * @param  {string} begintime 开始时间，格式'2017-03-16 12:00:11'
   * @param  {string} endtime   结束时间
   * @param  {number} firstHour 时间表开始每天开始时间
   * @return {Object}           时间段格子的位置信息和起止时间属性
   */
  function computeBoxPosition(begintime, endtime, firstHour) {
    if(firstHour == undefined) {
      firstHour = 0;
    }
    var dayIndex = (new Date(begintime.substr(0,10)).getDay() + 7 - 1) % 7; //从0开始
    var height = getDurationMinute(begintime, endtime) / ((24-firstHour)*60) * 100 + '%';

    var beginDateStr = begintime.substr(0,10);
    var beginTimeStr = addZero(firstHour)+':00:00';
    var basetime = beginDateStr + ' ' + beginTimeStr;

    var top = getDurationMinute(basetime, begintime) / ((24-firstHour)*60) * 100 + '%';

    return {
      dayIndex: dayIndex,
      height: height,
      top: top,
      begintime: begintime.substr(11,5),
      endtime: endtime.substr(11,5)
    }
  }

  /**
   *  解析时间规律字符串
   *
   * @param {string} rec_type [type]_[count]_[day]_[count2]_[days]#[extra]
   * @returns {Object}
   *  count           间隔
   *  day and count2  定义某月的某天
   *  days            定义每周的几天
   *  extra           额外的信息
   *
   */
  function parseRecType(rec_type) {
    var arr = rec_type.split('#');
    var patternArr = arr[0].split('_');
    var extra = arr[1] || '';

    return {
      type: patternArr[0],
      count: patternArr[1],
      day: patternArr[2],
      count2: patternArr[3],
      days: patternArr[4],
      extra: extra
    }
  }


  /**
   *  计算某月第几个星期几对应的日期
   *
   * @param {number} day     星期几
   * @param {number} count2  第几个星期
   * @param {Date} monthDate 日期
   * @returns {Date}         指定的某个星期的日期
   */
  function computeWeekDayOfMonth(day, count2, monthDate) {

    //该月第一天是星期几
    var firstDayDate = new Date(+monthDate - 24*3600*1000*(monthDate.getDate()-1));

    var nextMonthDate = new Date(monthDate.getFullYear(), monthDate.getMonth()+1);

    var firstDay = firstDayDate.getDay();

    var curDate = new Date(+firstDayDate + (day-firstDay+7)%7*24*3600*1000);
    var targetDateMS = +curDate + 24*3600*1000*7*(count2-1)
    if(targetDateMS < (+nextMonthDate)) {
      return new Date(targetDateMS);
    }
  }


  /**
   * 教师课时安排逻辑
   */
  function schedulerInit(config) {
    //教师uid
    var tuid = config.tuid;
    //教师时间url
    var url = config.url;
    //教师时间辅助url
    var helpUrl = config.helpUrl;

    //时间冲突检测url
    var checkUrl = config.checkUrl;
    //课程列表
    var courseList = config.courseList || [];
    // 上台人数（班型）
    var classtypes = config.classtypes || [];
    //创建时间段格子配置
    var create_lightbox = config.create_lightbox;
    //编辑时间段格子配置
    var edit_lightbox = config.edit_lightbox ||  config.create_lightbox;
    //创建时间段是否弹出
    var onCreate = config.onCreate || false;
    //背景颜色
    var bgColor = config.bgColor;
    //
    var buttons_left = config.buttons_left;
    var buttons_right = config.buttons_right;
    var icons_select = config.icons_select;

    //scheduler类型　1-教师工作时间 2-教师上课时间 3-机构课表
    var schedulerType = config.schedulerType;

    var folderid='';
    var foldername='';
    var auditors = [];
    var castinfo = {
      record: 0,
      live: 0,
      replay: 0
    };
    var webcastUrl='';
    var levelid = ''
    var levelname = ''

    scheduler.config.xml_date = "%Y-%m-%d %H:%i";
    scheduler.config.edit_on_create = onCreate;
    scheduler.config.details_on_create = onCreate;
    scheduler.config.dblclick_create = (tuid !=undefined);
    scheduler.config.details_on_dblclick= true;
    scheduler.config.show_loading = true;
    scheduler.config.auto_end_date = true;
    scheduler.config.first_hour = 6;

    //设置按钮布局
    scheduler.config.buttons_left = buttons_left || [];
    scheduler.config.buttons_right = buttons_right || ["dhx_save_btn", "dhx_cancel_btn","dhx_delete_btn"];

    //设置侧边icons
    scheduler.config.icons_select = icons_select || ['icon_details', 'icon_delete'];

    //在weekly设置中不包含过去时间
    scheduler.config.repeat_precise = true;

    // scheduler.config.include_end_by = true;

    scheduler.config.lightbox.sections = create_lightbox;

    //是否可以拖拽
    if(config.drag_move != undefined) {
      scheduler.config.drag_move = config.drag_move;
    }

    //自定义表单项
    scheduler.form_blocks["my_editor"] = {
      render:function(sns){
          return "<div class='dhx_cal_ltext my_editor' style='height:36px;'></div>";
      },

      set_value:function(node,value,ev) {
        if(ev.folderid != undefined && ev.foldername) {
          folderid = ev.folderid;
          foldername = ev.foldername;
        } else {
          folderid = undefined;
          foldername = '请选择课节资源'
        }
      },
      get_value:function(node,ev){
        ev.folderid = node.childNodes[0].getAttribute('data-value');
        ev.foldername = node.childNodes[0].getAttribute('title');
        console.log(ev.folderid);
        return node.childNodes[0].value;
      },
      focus:function(node){
          // var a=node.childNodes[1]; a.select(); a.focus();
      }
    }

    scheduler.form_blocks["audit"] = {
      render:function(sns){
          return "<div class='dhx_cal_ltext audit' style='height:36px;'></div>";
      },

      set_value:function(node,value,ev) {
        if(ev.auditors != undefined && ev.auditors.length) {
          auditors = ev.auditors;
        } else {
          auditors = []
        }
      },
      get_value:function(node,ev){
        ev.auditors = auditors
      },
      focus:function(node){
          // var a=node.childNodes[1]; a.select(); a.focus();
      }
    }

    scheduler.form_blocks["webcast"] = {
      render:function(sns){
          return "<div class='dhx_cal_ltext webcast' style='height:51px;'></div>";
      },

      set_value:function(node,value,ev) {
        if(ev.castinfo != undefined) {
          castinfo = ev.castinfo
          webcastUrl = ev.webcast
        } else {
          castinfo = {
            record: 0,
            live: 0,
            replay: 0
          }
          webcastUrl=''
        }
      },
      get_value:function(node,ev){
        ev.castinfo = castinfo
      },
      focus:function(node){
          // var a=node.childNodes[1]; a.select(); a.focus();
      }
    }

    scheduler.form_blocks["level"] = {
      render:function(sns){
          return "<div class='dhx_cal_ltext level' style='height:36px;'></div>";
      },
      set_value:function(node,value,ev) {
        //弹窗的时候获取值
        if(ev.levelid != undefined) {
          levelid = ev.levelid
        } else {
          levelid = ''
          levelname = ''
        }
      },
      get_value:function(node,ev){
        //保存的时候更新值
        ev.levelid = levelid
      },
      focus:function(node){}
    }

    scheduler.init('scheduler_here', new Date(), "week");

    // 未选中教师时不可操作
    scheduler.attachEvent("onBeforeEventCreated", function () {

      var allowFlag = true;
      switch (schedulerType) {
        case 1:
          break;
        case 2:
          if(tuid == undefined) {
            _Tips('请选择一名教师')
            allowFlag = false;
          }
          break;
        case 3:
          allowFlag = false;
      }
      return allowFlag
    });

    if(schedulerType == 2 && tuid == undefined) {
      return;
    }

    scheduler.attachEvent("onBeforeLightbox", function(event_id) {
			scheduler.resetLightbox();
			var ev = scheduler.getEvent(event_id);
			scheduler.config.lightbox.sections = (ev.edit) ? edit_lightbox : create_lightbox;

      if(schedulerType == 2 && ev.type == 2) {
        scheduler.config.lightbox.sections = config.read_lightbox
      }
			return true;
		});

    //阻止重绘，保证排课页面背景正常显示
    scheduler.attachEvent("onSchedulerResize", function(){
      return false;
    });

    if(schedulerType == 2) {
      scheduler.attachEvent("onLightbox", function (id ,ev){

        //课节资源
        var $my_editor = $('.dhx_cal_light .my_editor')
        var cloudFileInput=new CloudFileInput({
          selectorMode:'normal'
        });
        if(folderid != undefined) {
          cloudFileInput.setValue(folderid, foldername);
        }
        cloudFileInput.$dom.appendTo($my_editor);

        //旁听生
        var $audit = $('.dhx_cal_light .audit')

        function getAuditNameList(auditors) {
          var tips = '添加旁听生'
          if(auditors.length==0 || !Object.keys(auditors)) {
            return tips
          }

          return $.map(auditors, function (item) {
            return item.name
          }).join(',')
        }

        var auditNameList = getAuditNameList(auditors)
        var $auditBtn = $('<div class="btn btn-default">'+ auditNameList +'</div>').appendTo($audit);
        var checkedStudentList = [];
        $.each(auditors, function (i, item) {
          checkedStudentList.push({
            id: item.studentuid,
            name: item.name,
            phone: item.ClassInNo
          })
        })

        $auditBtn.on('click', function () {
          ajaxMethod({
            url: '/api/students',
            success: function (data, status) {
              if(status.code != 0) {
                return;
              }

              var candidateStudentList = []
              $.each(data, function (i, item) {
                candidateStudentList.push({
                  id: item.studentuid,
                  phone: item.ClassInNo,
                  name: item.name
                  // avatar: item.photo
                })
              })

              var studentSelector = new ContactSelector({
                candidateDataList: candidateStudentList,
                checkedDataList: checkedStudentList,
                hideAvatar: false,
                checkedMax: 20,
                callback: {
                  submit: function (checkedDataList) {
                    checkedStudentList = checkedDataList
                    auditors = Object.keys(checkedDataList)
                    $auditBtn.text(getAuditNameList(checkedDataList))
                  }
                }
              })
              studentSelector.$titleText.text('编辑旁听学生')
              studentSelector.popUpBox.show();
            }
          })
        })


        //网络状态
        var $webcast = $('.dhx_cal_light .webcast')
        var webcastBtnGroup=new WebcastCheckBtnGroup({
  				changeCallback: function(changedValue){
  					castinfo = {
  						record: Number(changedValue[0]),
  						live: Number(changedValue[1]),
  						replay: Number(changedValue[2])
  					}
  				}
  			});

        webcastBtnGroup.value([!!castinfo.record, !!castinfo.live, !!castinfo.replay]);

        /*if(this.data.webcastInfo.disabled() === true) {
  				webcastBtnGroup.recordBtn.disabled(true);
  				webcastBtnGroup.liveBtn.disabled(true);
  			}*/

        webcastBtnGroup.$dom.appendTo($webcast);
        if(castinfo.live || castinfo.replay) {
          $('<div style="margin-top:10px;color:#555;">直播 | 回放：<a href="'+ webcastUrl +'" style="color: #398dee;" target="_blank">'+ webcastUrl +'</a></div>').appendTo($webcast)
        }

        //课程级别
        var $level = $('.dhx_cal_light .level')
        var $levelBtn = $('<div class="btn btn-default">'+ (levelname ? levelname : '请选择课程级别') +'</div>').appendTo($level)
        if(levelid != '') {
          ajaxMethod({
            url: '/api/level/' + levelid,
            success: function (data, status) {
              if(status.code == 0) {
                levelname = data.title
                $levelBtn.text(levelname)
              }
            }
          })
        }

        $levelBtn.on('click', function () {
          var $wrapper =  $('<div class="level-admin">\
            <div id="tree" class="ztree"></div>\
          </div>')

          var popUpBox=new PopUpBox({
            type:'dom',
            style:'default contentScroll',
            submitBtnType:'confirm',
            titleText:'请选择',
            drag:true,
            show: true,
            content: $wrapper,
            callback:{
              yes: function (e) {
                var treeObj = $.fn.zTree.getZTreeObj('tree');
                var node = treeObj.getSelectedNodes()[0]

                if(node == null) {
                  _Tips('请选择课程级别')
                  return false
                }

                ajaxMethod({
                  url: '/api/level/' + node.id,
                  success: function (data, status) {
                    if(status.code == 0) {
                      levelid = node.id
                      levelname = data.title
                      $levelBtn.text(levelname)
                      popUpBox.close()
                    }
                  }
                })

                return false;
              }
            },
            position:{
              width:600,
              height:500
            }
          })

          levelTree({
            showRemoveBtn: function () {
              return false
            },
            showRenameBtn: function () {
              return false
            },
            showAddBtnFlag: false,
            setCurNode: function (wrapperIdName) {
              var treeObj = $.fn.zTree.getZTreeObj(wrapperIdName);
              var nodes = treeObj.getNodes();
              if (nodes.length > 0) {
                  var node = treeObj.getNodeByParam("id", levelid);
                  if (node) {
                    treeObj.selectNode(node);
                  }
              }
            }
          })

        })

      });
    }

    function eventSave(id, ev) {
      if(!ev.quotas) {
        _Tips("请填写总名额");
        return false;
      }

      if(isNaN(ev.quotas)) {
        _Tips("总名额必须为数字");
        return false;
      }

      if(ev.coursetypeid == '0') {
        _Tips("请选择课程类型");
        return false;
      }

      if(!ev.lessonname) {
        _Tips("请填写课节名称");
        return false;
      }

      if(ev.levelid == undefined || ev.levelid =='') {
        _Tips("请选择课程级别");
        return false;
      }

      /*if(ev.folderid == undefined) {
        _Tips("请选择课节资源");
        return false;
      }*/
      return true
    }

    function eventAdd(id, ev) {
      console.log('eventAdd');
      function postEventData(eventData) {
        function doAdd() {
          ajaxMethod({
            url: url,
            method: 'post',
            data: eventData,
            success: function (data, status) {
              if(status.code == 0) {
                // timeuid - 时间段格子的id，由服务器生成 标定一个有效的时间段
                // console.log(ev, ev.id, scheduler.getEvent(ev.id),data.data.timeuid);

                // 页面循环刷新后,会导致事件ID失效,只在添加单个时间段时生效
                var event = scheduler.getEvent(ev.id)
                if(event) {
                  event.timeuid = data.timeuid;
                  scheduler.updateEvent(ev.id);
                }
              } else {
                _Tips(status.message);
              }
              $('.dhx_cal_tab.active').click();
            }
          })
        }

        if(schedulerType == 1) {
          doAdd()
          return;
        }

        ajaxMethod({
          url: checkUrl,
          data: {
            checklist: [
              {
                teacheruid: eventData.teacheruid,
                begintime: eventData.begintime,
                endtime: eventData.endtime
              }
            ]
          },
          success: function (data, status) {
            if(status.code == 0) {

              var checkFlag = true;
              $.each(data, function (i, item) {
                if(item.status == false) {
                  _Tips('时间冲突,请重新操作')
                  return checkFlag = false;
                }
              })

              if(!checkFlag) {
                $('.dhx_cal_tab.active').click();
                return;
              }
              doAdd()
            }
          }
        })

      }

      function addLessonDetail(eventData) {
        $.extend(eventData, {
          type: 1,
          quotas: ev.quotas,
          usequotas: 0,
          coursetypeid: ev.coursetypeid,
          classtypeid: ev.classtypeid,
          coursetypename: getCourseNameById(courseList, ev.coursetypeid),
          name: ev.lessonname,
          folderid: ev.folderid,
          foldername: ev.foldername,
          auditors: ev.auditors,
          castinfo: ev.castinfo
        })
      }

      if(ev.rec_type) {
        var event_length = ev.event_length;
        var rec_type = ev.rec_type;
        console.log(rec_type);

        var beginDateMS = +ev.start_date;
        var endDateMS = +ev.end_date;

        var recData = parseRecType(rec_type);
        var eventDataList = [];
        switch (recData.type) {
          case 'day':
            var workDayFlag = (recData.days != '');
            for(var i = beginDateMS; i < endDateMS; i += 24*3600*1000* recData.count ) {
              var eventData = {
                begintime: new Date(i).Format('YYYY-MM-DD hh:mm'),
                endtime: new Date(i + event_length*1000).Format('YYYY-MM-DD hh:mm'),
                text: ev.text,
                teacheruid: tuid
              };

              addLessonDetail(eventData)

              postEventData(eventData);
            }

            break;
          case 'week':
            var days = recData.days.split(',');
            var stepDay = (new Date(beginDateMS).getDay() + 6) % 7;

            //开始日期该星期第一天
            var mondayMS = +new Date(beginDateMS) - stepDay*24*3600*1000;
            for(var i = beginDateMS; i < endDateMS; i += 24*3600*1000*7* recData.count, mondayMS += 24*3600*1000*7* recData.count) {
              $.each(days, function(i,v){
                var dayIndex = (Number(v) + 6) % 7;
                var curDateMS = mondayMS + dayIndex*24*3600*1000;

                //当前设置时间必须在开始和结束时间之间
                if(curDateMS < beginDateMS || curDateMS >= endDateMS) {
                  return true;
                }

                var eventData = {
                  begintime: new Date(curDateMS).Format('YYYY-MM-DD hh:mm'),
                  endtime: new Date(mondayMS + dayIndex*24*3600*1000 + event_length*1000).Format('YYYY-MM-DD hh:mm'),
                  text: ev.text,
                  teacheruid: tuid
                };

                addLessonDetail(eventData)

                postEventData(eventData);

              })
            }

            break;
          case 'month':
            var day = Number(recData.day);
            var count2 = Number(recData.count2);
            for(var i = beginDateMS; i < endDateMS;) {
              var curDate = computeWeekDayOfMonth(day, count2, new Date(i));
              if(curDate) {
                var eventData = {
                  begintime: new Date(+curDate).Format('YYYY-MM-DD hh:mm'),
                  endtime: new Date(+curDate + event_length*1000).Format('YYYY-MM-DD hh:mm'),
                  text: ev.text,
                  teacheruid: tuid
                };

                addLessonDetail(eventData)

                postEventData(eventData);
              }

              i += 24*3600*1000* recData.count* new Date(i).getMonthDateMax()
            }

            break;
        }

      } else {
        var eventData = {
          text: ev.text,
          teacheruid: tuid,
          begintime: ev.start_date.Format('YYYY-MM-DD hh:mm'),
          endtime: ev.end_date.Format('YYYY-MM-DD hh:mm')
        }

        if(schedulerType == 2) {
          addLessonDetail(eventData)
        }

        postEventData(eventData);
      }

      return true;
    }

    function eventEdit(id, ev) {
        //console.log('eventEdit');
        var eventData = {
          teacheruid: tuid,
          begintime: ev.start_date.Format('YYYY-MM-DD hh:mm'),
          endtime: ev.end_date.Format('YYYY-MM-DD hh:mm'),
          scheduleid: ev.timeuid
        }

        if(schedulerType == 2) {
          $.extend(eventData, {
            quotas: ev.quotas,
            coursetypeid: ev.coursetypeid,
            classtypeid: ev.classtypeid,
            coursetypename: getCourseNameById(courseList, ev.coursetypeid),
            name: ev.lessonname,
            folderid: ev.folderid,
            foldername: ev.foldername,
            auditors: ev.auditors,
            castinfo: ev.castinfo,
            levelid: ev.levelid
          })
        }

        ajaxMethod({
          url: url + '/' + ev.timeuid,
          method: 'put',
          data: eventData,
          success: function(data, status) {
            if(status.code == 0) {
              scheduler.updateEvent(ev.id)
            } else {
              _Tips(status.message)
            }
            $('.dhx_cal_tab.active').click();
          }
        })

    }

    function eventDelete(id, ev) {
      //return false 阻止页面重绘

      if(ev.timeuid == undefined) {
          return false;
      }
      ajaxMethod({
        url: url + '/' + ev.timeuid,
        method: 'delete',
        success: function (data, status) {
          if(status.code != 0) {
            _Tips(status.message)
          }
          $('.dhx_cal_tab.active').click();

          // scheduler.updateView(new Date(), "week")
          // scheduler.setCurrentView(new Date(ev.start_date.Format('YYYY-MM-DD hh:mm')), "week")
          // alert(data.status.statustext)
        }
      })
      return false;
    }


    if(schedulerType == 2) {
      scheduler.attachEvent("onEventSave", eventSave)
    }
    scheduler.attachEvent("onEventAdded", eventAdd);
    scheduler.attachEvent("onEventChanged", eventEdit);
    scheduler.attachEvent("onEventDeleted", eventDelete);


    function getCourseTable(begintime, endtime, onlyBg) {
      console.log(begintime, endtime);

      //toggle
      var tmpVal;
      if(+new Date(begintime) > +new Date(endtime)) {
        var tmpVal = begintime;
        begintime = endtime;
        endtime = tmpVal;
      }

      scheduler.clearAll();

      if(helpUrl) {
        ajaxMethod({
          url: helpUrl,
          data: {
            teacheruid: tuid,
            begintime: begintime,
            endtime: endtime
          },
          success: function (data) {
            $.each(data, function () {
              var boxPos = computeBoxPosition(this.begintime, this.endtime, scheduler.config.first_hour);
              var $bgBox = $('<div class="bg-box"></div>').text(boxPos.begintime + ' - ' + boxPos.endtime);
              $bgBox.css({
                top: boxPos.top,
                height: boxPos.height
              });

              $('.dhx_cal_data>div').eq(boxPos.dayIndex).append($bgBox)
            })
          }
        })
      }

      if(onlyBg) {
        return;
      }


      var postData = {}
      switch (schedulerType) {
        case 1:
        case 2:
          postData = {
            teacheruid: tuid,
            begintime: begintime,
            endtime: endtime
          }
          break;
        case 3:
          postData = {
            begintime: begintime,
            endtime: endtime,
            status: 1
          }
          break;
      }

      ajaxMethod({
        url: url+'s',
        data: postData,
        success: function (data) {
          if(typeof config.processData == 'function') {
            var dataArr = config.processData(data, courseList);
            scheduler.parse(dataArr, 'json')
          }
        }
      })
    }

    var dateRange = getWeekDateRange()
    getCourseTable(dateRange.begintime, dateRange.endtime)

    /**
     * [transFormDateText 解析非标准格式的日期]
     * @param  {string} dateText  比如'2017年4月10日'
     * @return {Date}
     */
    function transFormDateText(dateText) {
      var prefix = '-'
      var dateStr = dateText.replace(/(\d{1,4})\D+/g, function () {
        if(arguments[2] == 0) {
          return arguments[1]
        } else {
          return prefix + arguments[1]
        }
      })
      return new Date(dateStr)
    }

    /**
     * 获取某个日期所在周的日期范围
     * @inner
     * @param  {Date} curDate 输入日期对象
     * @return {Object}       包含两个属性，分别是该周第一天和下周的第一天
     */
    function getWeekDateRange(curDate) {
      curDate || (curDate = new Date())
      var curDay = curDate.getDay();
      var dayIndex = (curDay+6) % 7; // 0 - 6
      return {
        begintime: new Date(+curDate - dayIndex*24*3600*1000).Format('YYYY-MM-DD'),
        endtime: new Date(+curDate + (7-dayIndex)*24*3600*1000).Format('YYYY-MM-DD')
      }
    }

    /**
     * 获取某个日期所在月份的日期范围
     * @inner
     * @param  {Date} curDate 输入日期对象
     * @return {Object}       包含两个属性，分别是该月第一天和下个月的第一天
     */
    function getMonthDateRange(curDate) {
      curDate || (curDate = new Date());
      var curYear = curDate.getFullYear();
      var curMonth = curDate.getMonth();
      return {
        begintime: new Date(curYear, curMonth).Format('YYYY-MM-DD'),
        endtime: new Date(curYear, curMonth+1).Format('YYYY-MM-DD')
      }
    }

    //定义next按钮行为
    $('.dhx_cal_next_button,.dhx_cal_prev_button').on('click', function () {
      var tabType = $('.dhx_cal_tab.active').attr('name')
      var ariaLabel = $('.dhx_cal_date').attr('aria-label')
      var begintime, endtime;
      switch (tabType) {
        case 'day_tab':
          var curDate = transFormDateText(ariaLabel)
          begintime = new Date(+curDate).Format('YYYY-MM-DD'); //next day
          endtime = new Date(+curDate + 24*3600*1000).Format('YYYY-MM-DD');// next two days
          break;
        case 'week_tab':
          var curMondayDate = transFormDateText(ariaLabel.split('&ndash;')[0])
          begintime = new Date(+curMondayDate).Format('YYYY-MM-DD'); //next week
          endtime = new Date(+curMondayDate + 7*24*3600*1000).Format('YYYY-MM-DD');// next two weeks
          break;
        case 'month_tab':
          var curDate = transFormDateText(ariaLabel)
          var curYear = curDate.getFullYear()
          var curMonth = curDate.getMonth()
          begintime = new Date(curYear, curMonth).Format('YYYY-MM-DD'); //next month
          endtime = new Date(curYear, curMonth+1).Format('YYYY-MM-DD'); // next two months
          break;
      }
      getCourseTable(begintime, endtime)
    })

    //定义today按钮行为
    $('.dhx_cal_today_button').on('click', function () {
      var tabType = $('.dhx_cal_tab.active').attr('name');
      var todayDate = new Date();
      var begintime, endtime;
      switch (tabType) {
        case 'day_tab':
          begintime = todayDate.Format('YYYY-MM-DD');
          endtime = new Date(+todayDate + 24*3600*1000).Format('YYYY-MM-DD');
          break;
        case 'week_tab':
          var dateRange = getWeekDateRange()
          begintime = dateRange.begintime;
          endtime = dateRange.endtime;
          break;
        case 'month_tab':
          var curYear = todayDate.getFullYear()
          var curMonth = todayDate.getMonth()
          begintime = todayDate.Format('YYYY-MM-DD'); //current month
          endtime = new Date(curYear, curMonth+1).Format('YYYY-MM-DD'); // next month
          break;
      }
      getCourseTable(begintime, endtime)
    })

    //定义week按钮行为
    $('.dhx_cal_tab[name="week_tab"]').on('click', function (e) {
     /* if($(this).hasClass('active')) {
        return;
      }*/

      var ariaLabel = $('.dhx_cal_date').attr('aria-label');
      var dateRange = getWeekDateRange(transFormDateText(ariaLabel.split('&ndash;')[0]));
      getCourseTable(dateRange.begintime, dateRange.endtime);
    });

    //定义month按钮行为
    $('.dhx_cal_tab[name="month_tab"]').on('click', function () {
     /* if($(this).hasClass('active')) {
        return;
      }*/

      var tabType = $('.dhx_cal_tab.active').attr('name');
      var ariaLabel = $('.dhx_cal_date').attr('aria-label');
      var curDate;
      if(tabType == 'day_tab') {
        curDate = transFormDateText(ariaLabel);
      } else {
        curDate = transFormDateText(ariaLabel.split('&ndash;')[0]);
      }

      var dateRange = getMonthDateRange(curDate);
      getCourseTable(dateRange.begintime, dateRange.endtime);
    })
  }

  window.schedulerInit = schedulerInit;

})
